package com.multysite.ajax.admin;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.multysite.entity.Category;
import com.multysite.model.CategoryModel;
import com.multysite.util.StringHelper;

@SuppressWarnings("serial")
public class ProcessCategory extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			String action = request.getParameter("action");
			if (action != null && action.equals("add")) {
				String title = request.getParameter("title");
				title = URLDecoder.decode(title, "UTF-8");
				String alias = StringHelper.replaceVietnamese(title);
				Category obj = CategoryModel.getById(alias);
				if (obj != null) {
					response.getWriter().println("1");
				} else {
					obj = new Category();
					obj.setTitle(title);
					obj.setAlias(alias);
					String parentAlias = request.getParameter("parent");
					if (!parentAlias.equals("0")) {
						obj.setParentAlias(parentAlias);
						obj.setLevel(2);
					} else {
						obj.setLevel(1);
					}
					CategoryModel.insert(obj);
					response.setCharacterEncoding("UTF-8");
					response.getWriter().println(
							obj.getAlias() + "," + obj.getLevel());
				}
			}
		} catch (Exception e) {
			response.getWriter().println(
					"Error when processing, please try again later !");
		}
	}
}
